package com.sunchangming.stmdb.xgen;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@XStreamAlias("bean")
public class Bean extends UserType {
	ArrayList<Variable> vars = new ArrayList<Variable>();

	@XStreamAsAttribute
	public String baseclass;

	private Variable keyVar;

	public Variable getKeyVar() {
		return keyVar;
	}

	public void generateCode(Path src, String language) throws IOException, TemplateException {
		final Path outputFile = parent.getDir(src).resolve(name + ".java");
		final freemarker.template.Configuration cfg = Main.getFreeMarkerConfig();
		final Template tmpl = cfg.getTemplate("beaninterface.tmpl");
		final Map<Object, Object> root = new HashMap<Object, Object>();
		root.put("packagename", parent.getFullName());
		root.put("classname", name);
		root.put("vars", vars);
		root.put("keyVar", keyVar);
		root.put("baseclass", baseclass);
		tmpl.process(root, new OutputStreamWriter(Files.newOutputStream(outputFile), "utf-8"));
	}

	public String getBaseclass() {
		return baseclass;
	}

	void compile() {
		for (final Variable v : vars) {
			v.compile();
		}
	}

}
